package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.bo.SysTenantAddBo;
import com.ruoyi.system.domain.bo.SysTenantBo;
import com.ruoyi.system.domain.bo.SysTenantEditBo;
import com.ruoyi.system.domain.bo.SysTenantQueryBo;
import com.ruoyi.system.domain.SysTenant;
import com.ruoyi.system.mapper.SysTenantMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.system.domain.vo.SysTenantVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 租户Service业务层处理
 *
 * @author lingdeng
 * @date 2021-07-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysTenantServiceImpl implements ISysTenantService {

    private final SysTenantMapper baseMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询租户
     *
     * @param tenantId 租户主键
     * @return 租户
     */
    @Override
    public SysTenantVo queryById(Long tenantId) {
        return baseMapper.selectVoById(tenantId);
    }

    /**
     * 查询租户列表
     *
     * @param bo 租户
     * @return 租户
     */
    @Override
    public TableDataInfo<SysTenantVo> queryPageList(SysTenantBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysTenant> lqw = buildQueryWrapper(bo);
        Page<SysTenantVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询租户列表
     *
     * @param bo 租户
     * @return 租户
     */
    @Override
    public List<SysTenantVo> queryList(SysTenantBo bo) {
        LambdaQueryWrapper<SysTenant> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysTenant> buildQueryWrapper(SysTenantBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysTenant> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTenantName()), SysTenant::getTenantName, bo.getTenantName());
        lqw.eq(StringUtils.isNotBlank(bo.getLeader()), SysTenant::getLeader, bo.getLeader());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SysTenant::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), SysTenant::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysTenant::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增租户
     *
     * @param bo 租户
     * @return 结果
     */
    @Override
    public Boolean insertByBo(SysTenantBo bo) {
        SysTenant add = BeanUtil.toBean(bo, SysTenant.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTenantId(add.getTenantId());
        }
        return flag;
    }

    /**
     * 修改租户
     *
     * @param bo 租户
     * @return 结果
     */
    @Override
    public Boolean updateByBo(SysTenantBo bo) {
        SysTenant update = BeanUtil.toBean(bo, SysTenant.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysTenant entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除租户
     *
     * @param ids 需要删除的租户主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 取消授权用户角色
     *
     * @param user 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUser user) {
        SysUser entity = sysUserMapper.selectUserById(user.getUserId());
        entity.setUserType("02");
        return sysUserMapper.updateById(entity);
    }

    /**
     * 批量取消授权用户租户
     *
     * @param tenantId 租户ID
     * @param userIds  需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long tenantId, Long[] userIds) {
        SysUser entity = new SysUser();
        entity.setUserType("02");
        return sysUserMapper.update(entity, new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserType, "01")
            .in(SysUser::getUserId, Arrays.asList(userIds)));
    }

    /**
     * 批量选择授权用户租户
     *
     * @param tenantId 租户ID
     * @param userIds  需要删除的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long tenantId, Long[] userIds) {
        // 新增用户与租户管理
        SysUser entity = new SysUser();
        entity.setUserType("01");
        entity.setTenantId(tenantId);
        return sysUserMapper.update(entity, new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserType, "02")
            .in(SysUser::getUserId, Arrays.asList(userIds)));
    }
}
